local table = KEYS[1];
local primaryKey = KEYS[2];
local indexHashes = KEYS[3];
local data = KEYS[4];


function string.split(szFullString, szSeparator)
    local nFindStartIndex = 1
    local nSplitIndex = 1
    local nSplitArray = {}
    while true do
        local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex)
        if not nFindLastIndex then
            nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString))
            break
        end
        nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)
        nFindStartIndex = nFindLastIndex + string.len(szSeparator)
        nSplitIndex = nSplitIndex + 1
    end
    return nSplitArray
end


-- 删除历史索引
local field = table .. ":" .. primaryKey
local indexVal = redis.call('hget', indexHashes, field);
if indexVal then
    local indexValArray = string.split(indexVal, ',');
    for i, v in ipairs(indexValArray) do
        local splitArray = string.split(v, ':');
        if splitArray[2] == 'index' then
            -- 聚集索引
            redis.call('srem', table .. ":index:" .. splitArray[1] ..":".. splitArray[3], primaryKey);
        elseif splitArray[2] == 'unique' then
            -- 唯一索引
            redis.call('hdel', table .. ":unique:", splitArray[1] ..":".. splitArray[3]);
        end
    end
end


-- 添加历史索引
indexVal = "";
for i, v in ipairs(ARGV) do
    local splitArray = string.split(v, ':');
    -- 设置新的索引
    if splitArray[2] == 'index' then
        -- 聚集索引
        redis.call('sadd', table .. ":index:" .. splitArray[1] ..":".. splitArray[3], primaryKey);
    elseif splitArray[2] == 'unique' then
        -- 唯一索引
        redis.call('hset', table .. ":unique:", splitArray[1] ..":".. splitArray[3], primaryKey);
    end
    if i > 1 then
        indexVal = indexVal .. "," .. v
    else
        indexVal = indexVal .. v
    end
end


-- 设置索引值
redis.call('hset', indexHashes, field, indexVal);
-- 设置对象值
redis.call('hset', table, primaryKey, data);